package com.juejin.www.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.juejin.www.dao.NoticeDao;
import com.juejin.www.model.DTO.PageDTO;
import com.juejin.www.model.VO.AuditVO;
import com.juejin.www.model.VO.NoticeVO;
import com.juejin.www.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Jacky
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeDao noticeDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageDTO<NoticeVO> getNotices(Integer currentPage, Integer pageSize, Integer recipient) {
        Integer begin = (currentPage - 1) * pageSize;
        List<NoticeVO> rows = noticeDao.getNotices(begin,pageSize,recipient);
        Integer totalCount = noticeDao.getNoticesTotalCount(recipient);
        PageDTO<NoticeVO> notices = new PageDTO<>(totalCount,rows);
        return notices;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AuditVO getAuditResult(Integer id,Integer auditId) {
        String key = "auditResult:"+auditId;
        String cacheValue = stringRedisTemplate.opsForValue().get(key);
        AuditVO auditResult;
        if(cacheValue!=null){
            auditResult = JSON.parseObject(cacheValue,AuditVO.class);
        }else {
            auditResult = noticeDao.getAuditResult(auditId);
            stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(auditResult));
            noticeDao.updateIsRead(id);
        }
        return auditResult;
    }

    @Override
    public Integer getIsNotReadCount(Integer recipient) {
        Integer isNotReadCount = noticeDao.getIsNotReadCount(recipient);
        return isNotReadCount;
    }
}
